<script setup>
import { onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';



const active = ref(0)
const router = useRouter()
const route = useRoute()

onMounted(() => {
  // console.log(router)
  const data = router.options.routes[0]
  active.value = data.children.findIndex(item => '/' + item.path === route.path)
})

// 补充watch监听路由变化
watch(
  () => route.path,
  (newPath) => {
    // 优先使用跳转时设置的activeTab，否则根据当前路径匹配
    const activeTab = localStorage.getItem('activeTab') || newPath;
    const index = router.options.routes[0].children.findIndex(
      item => `/${item.path}` === activeTab
    );
    if (index !== -1) {
      active.value = index;
    }
    // 清除临时存储的activeTab
    localStorage.removeItem('activeTab');
  },
  { immediate: true } // 初始化时执行一次
);


</script>
<template>
  <RouterView></RouterView>
  <van-tabbar v-model="active">
    <van-tabbar-item v-for="item in router.options.routes[0].children" :key="item.path" :icon="item.meta.icon"
      :url="`#/${item.path}`">{{ item.meta.name }}</van-tabbar-item>
  </van-tabbar>
</template>
<style scoped></style>